package cn.jdy.anquan.service;

import cn.jdy.anquan.entity.CompanySafe;
import cn.jdy.common.constant.GlobalConstant;
import cn.jdy.framework.db.hibernate.BaseDao;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.StringUtil;
import cn.jdy.platform.entity.ConfValue;
import cn.jdy.platform.service.ConfService;
import cn.jdy.plugins.entity.Info;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.SimpleExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.beans.IntrospectionException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author luzhirui
 * @title : 中小企业资料库操作实现
 */
@Service
public class CompanySafeService extends BaseDao<CompanySafe> {
  @Autowired
  private ConfService confService;

 
  /**
   * 查询中小企业资料
   * web专用
   * @return
   */
  public Map<String, Object> search(CompanySafe entity) throws IntrospectionException {
    Map<String, Object> map = new HashMap<String, Object>();
    // 准备拼接sql元素
    DetachedCriteria dc = DetachedCriteria.forClass(super.entityClass);
    StringBuilder url = new StringBuilder();// URL参数，翻页使用
    String typeId = entity.getTypeId();
    String province = entity.getProvince();
    String city = entity.getCity();
    String county = entity.getCounty();
    String sSearch = entity.getsSearch();
    String keywords = entity.getKeywords();
    boolean indistinct = keywords != null && keywords.length() > 0;// 是否模糊搜索
    // 是否使用关键字模糊查询
    if (indistinct) {
      dc.createAlias("company", "c");// 设置别名 为关联company表c.companyName
      dc.add(Restrictions.or(
          Restrictions.like("c.companyName", keywords, MatchMode.ANYWHERE),
          Restrictions.like("linkMan",  keywords, MatchMode.ANYWHERE),
          Restrictions.like("tel",  keywords, MatchMode.ANYWHERE),
          Restrictions.like("website",  keywords, MatchMode.ANYWHERE),
          Restrictions.like("icp",  keywords, MatchMode.ANYWHERE),
          Restrictions.like("pcp",  keywords, MatchMode.ANYWHERE),
          Restrictions.like("linkTel",  keywords, MatchMode.ANYWHERE)
      ));
      url.append("&keywords=").append(keywords);
    }
    // 判断过滤条件
    if (typeId != null && !typeId.isEmpty()) {
      url.append("&typeId=").append(typeId);
      dc.add(Restrictions.eq("typeId", typeId));
    }
    if (province != null && !province.isEmpty()) {
      url.append("&province=").append(province);
      dc.add(Restrictions.eq("province", province));
    } 
    if (city != null && !city.isEmpty()) {
      url.append("&city=").append(city);  
      dc.add(Restrictions.eq("city", city));
    } 
    if (county != null && !county.isEmpty()) {
      url.append("&county=").append(county);
      dc.add(Restrictions.eq("county", county));
    }
    
    // sql拼接排序条件
    if (sSearch != null && sSearch.length() > 0) {
      dc.addOrder(entity.isAsc() ? Order.asc(sSearch) : Order.desc(sSearch));
      url.append("&sSearch=").append(sSearch).append("&asc=").append(entity.isAsc());
    } else {// 默认排序
      dc.addOrder(Order.desc("createTime"));
      url.append("&sSearch=").append("createTime").append("&asc=").append(entity.isAsc());
    }
    
    map.put("dataList", super.find(dc, entity.getiDisplayStart(), entity.getiDisplayLength()));
    map.put("total", super.count(dc));
    if (url.length() > 1)
      map.put("url", url.append("&").substring(1));
    return map;
  }
  
  /**
   * 查询中小企业资料
   * 后台管理专用
   * @return
   */
  public Map<String, Object> search(CompanySafe entity, String fromDate, String toDate) throws IntrospectionException {
    Map<String, Object> map = new HashMap<>();
    // 准备拼接sql元素
    DetachedCriteria dc = DetachedCriteria.forClass(super.entityClass);
    StringBuilder url = new StringBuilder();// URL参数，翻页使用
    String typeId = entity.getTypeId();
    String province = entity.getProvince();
    String city = entity.getCity();
    String county = entity.getCounty();
    String sSearch = entity.getsSearch();
    String keywords = entity.getKeywords();
    boolean indistinct = StringUtil.isNotEmpty(keywords) && StringUtil.isEmpty(entity.getKeyType());// 是否模糊搜索
    List<SimpleExpression> ors = new ArrayList<>();
    // 是否使用关键字模糊查询
    dc.createAlias("company", "company");
    if (indistinct) {
      ors.add(Restrictions.like("company.companyName", keywords, MatchMode.ANYWHERE));
      ors.add(Restrictions.like("linkMan", keywords, MatchMode.ANYWHERE));
      url.append("&keywords=").append(keywords);
      List<ConfValue> bClass = confService.queryByType(GlobalConstant.TYPE_BUSINESS, null);
      for (ConfValue cv : bClass) {
        if (keywords.equals(cv.getValue0())) {
          typeId = String.valueOf(cv.getId());
          entity.setTypeId(typeId);
          break;
        }
      }
    }else if(StringUtil.isNotEmpty(keywords) && StringUtil.isNotEmpty(entity.getKeyType())) {
      dc.add(Restrictions.like(entity.getKeyType(), keywords, MatchMode.ANYWHERE));
    }
    // 判断过滤条件
    if (typeId != null && !typeId.isEmpty()) {
      url.append("&typeId=").append(typeId);
      dc.add(Restrictions.eq("typeId", typeId));
    } else if (indistinct) {
      ors.add(Restrictions.like("typeId", keywords, MatchMode.ANYWHERE));
    }
    if (province != null && !province.isEmpty()) {
      url.append("&province=").append(province);
      dc.add(Restrictions.eq("province", province));
    } else if (indistinct) {
      ors.add(Restrictions.like("province", keywords, MatchMode.ANYWHERE));
    }
    if (city != null && !city.isEmpty()) {
      url.append("&city=").append(city);
      dc.add(Restrictions.eq("city", city));
    } else if (indistinct) {
      ors.add(Restrictions.like("city", keywords, MatchMode.ANYWHERE));
    }
    if (county != null && !county.isEmpty()) {
      url.append("&county=").append(county);
      dc.add(Restrictions.eq("county", county));
    } else if (indistinct) {
      ors.add(Restrictions.like("county", keywords, MatchMode.ANYWHERE));
    }
    if (StringUtil.isNotEmpty(entity.getStatus())) {
      dc.add(Restrictions.eq("status", entity.getStatus()));
    }
    SimpleExpression[] criterions = new SimpleExpression[ors.size()];
    ors.toArray(criterions);
    dc.add(Restrictions.or(criterions));

    // sql拼接排序条件
    if (sSearch != null && sSearch.length() > 0) {
      dc.addOrder(entity.isAsc() ? Order.asc(sSearch) : Order.desc(sSearch));
      url.append("&sSearch=").append(sSearch).append("&asc=").append(entity.isAsc());
    } else {// 默认排序
      dc.addOrder(Order.desc("createTime"));
      url.append("&sSearch=").append("createTime").append("&asc=").append(entity.isAsc());
    }

    if(StringUtil.isNotEmpty(fromDate)) {
      if(StringUtil.isNotEmpty(toDate)) {
        dc.add(Restrictions.between("createTime", fromDate, toDate));
      }else {
        dc.add(Restrictions.ge("createTime", fromDate));
      }
    }else if(StringUtil.isNotEmpty(toDate)) {
      dc.add(Restrictions.le("createTime", toDate));
    }

    map.put("dataList", super.find(dc, entity.getiDisplayStart(), entity.getiDisplayLength()));
    map.put("total", super.count(dc));
    if (url.length() > 1)
      map.put("url", url.append("&").substring(1));
    return map;
  }

  /**
   * 获取企业top数
   */
  public List<CompanySafe> getTop(int limitMax) {
    DetachedCriteria dc = DetachedCriteria.forClass(entityClass);
    dc.addOrder(Order.desc("createTime"));
    return super.find(dc,0,limitMax);

//    String sql = "select c.id,c.companyName as name,cs.createTime,cs.website from companysafe cs,company c where cs.`companyId` = c.`id` order by cs.createTime desc limit 0,?";
//    SQLQuery query = super.em().createSQLQuery(sql);
//    query.setParameter(0, n);
//    // 将查询寻结果转换为Map格式，解决多表查询或零散字段查询 映射取值问题
//    query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
//    return query.list();

  }
  
  /**
   * 查询总条数
   *
   * @return
   */
  public String getCount(CompanySafe bo) {
    try {
      return String.valueOf(count(createFilter(bo)));
    } catch(Exception e) {
      BaseLog.e(this.getClass(), " 查询我的网站总条数失败", e);
    }
    return null;
  }
  
  /**
   * 查询我的网站
   *
   * @return
   */
  @SuppressWarnings("unchecked")
  public List<CompanySafe> query(CompanySafe bo) {
    List<CompanySafe> list = null;
    try {
      DetachedCriteria dc = createFilter(bo);
      list =  find(dc,bo.getiDisplayStart(),bo.getiDisplayLength());
    } catch(Exception e) {
      BaseLog.e(this.getClass(), "查询我的消网站信息异常", e);
    }
    return list;
  }
 
  
  private DetachedCriteria createFilter(CompanySafe bo){
    DetachedCriteria dc = DetachedCriteria.forClass(entityClass);
    if(StringUtil.isNotEmpty(bo.getStatus())){
      dc.add(Restrictions.eq("status", bo.getStatus()));
    }
    if(bo.getCompany()!=null && bo.getCompany().getId()>0){
      dc.add(Restrictions.eq("companyId", bo.getCompany().getId()));
    }
    
    return dc;
  }
}
